//
//  RegistViewController.m
//  YiXiProject
//
//  Created by iMac on 2019/7/15.
//  Copyright © 2019 iMac. All rights reserved.
//

#import "RegistViewController.h"

#import "RegistView.h"               // 当前要显示的View视图头文件
#import "HomeMarryViewController.h"  // 首页

#import <AssetsLibrary/AssetsLibrary.h>

@interface RegistViewController () <RegistPageDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic,strong) RegistView *regView;     // View属性
@property (nonatomic,assign) NSInteger isImg;         // 图片路径
@property (nonatomic,strong) UIImage *imgdata;
@property (nonatomic,strong) NSString *imgstring;     // 头像上传成功后获取到的路径

@end

@implementation RegistViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //注册键盘弹出通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    //注册键盘隐藏通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    _isImg = 0;
    
    [self creatRegView];     // 初始化登陆页面ui
    
}
#pragma mark -- 初始化登陆页面ui
-(void)creatRegView
{
    [self.navigationController setNavigationBarHidden:YES];
    
    self.regView = [[RegistView alloc]init];
    self.regView.delegate = self;
    [self.view addSubview:self.regView];
    self.regView.sd_layout.leftSpaceToView(self.view, 0).topSpaceToView(self.view, 0).rightSpaceToView(self.view, 0).bottomSpaceToView(self.view, 0);
        
    // 变色器
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = self.view.frame;
    gradient.colors = [NSMutableArray arrayWithObjects:
                       (id)ColorAlphe(250, 94, 99, 1).CGColor,
                       (id)ColorAlphe(227, 40, 118, 1).CGColor,
                       nil];
    
    //可以实现横向渐变色   对角方向渐变色
    gradient.startPoint = CGPointMake(0, 0);
    gradient.endPoint = CGPointMake(0, 1);
    [self.view.layer insertSublayer:gradient atIndex:0];
    
}

-(void)clickregistPageButton:(NSInteger)tag
{
    switch (tag) {
        case 100:
            [self dismissViewControllerAnimated:YES completion:nil];
            break;
        case 101:
            [self requestUpload];
            break;
        case 102:
            [self.navigationController popViewControllerAnimated:YES];
            break;
            
        default:
            break;
    }
}

// 注册时先把上传图片获取到网络地址
-(void)requestUpload
{
    if(_isImg == 0)
    {
        [SVProgressHUD showErrorWithStatus:@"请选择您的头像"];
        [SVProgressHUD dismissWithDelay:SVPROGRESSHUDTIME];
    }
    else
    {
        [HttpDatas requestImgUploadFile:self.imgdata success:^(id  _Nonnull json) {
            
            if([json isKindOfClass:[NSDictionary class]])
            {
                if([json[@"status"]integerValue] == 200)
                {
                    self.imgstring = json[@"data"];
                    
                    [self clickregistButton];
                }
            }
            
        } failure:^(NSError * _Nonnull err) {
            [SVProgressHUD showErrorWithStatus:@"注册失败"];
            [SVProgressHUD dismissWithDelay:SVPROGRESSHUDTIME];
        }];
    }
    
}

//头像上传成功 执行这里，然后通过接口把用户注册信息传给后台
-(void)clickregistButton
{
    [HttpDatas requestRegistUser_type:@"1" name:self.regView.nameText.text email:self.regView.emailText.text password:self.regView.passText.text photo:self.imgstring success:^(id  _Nonnull json) {
        
        if([json isKindOfClass:[NSDictionary class]])
        {
            if([json[@"status"]integerValue] == 200)
            {
                [YXUserdefaults PutDefaults:@"name" Value:self.regView.nameText.text];
                [YXUserdefaults PutDefaults:@"email" Value:self.regView.emailText.text];
                [YXUserdefaults PutDefaults:@"password" Value:self.regView.passText.text];
                [YXUserdefaults PutDefaults:@"isLogin" Value:@"YES"];
                [YXUserdefaults PutDefaults:@"token" Value:json[@"data"][@"token"]];
                [YXUserdefaults PutDefaults:@"user_id" Value:json[@"data"][@"id"]];
                
                HomeMarryViewController *homeVC = [[HomeMarryViewController alloc]init];
                UINavigationController *navRoot = [[UINavigationController alloc]initWithRootViewController:homeVC];
                KeyWindow.rootViewController = navRoot;
                
                [SVProgressHUD showSuccessWithStatus:@"注册成功"];
                [SVProgressHUD dismissWithDelay:SVPROGRESSHUDTIME];
            }
            else
            {
                [SVProgressHUD showSuccessWithStatus:json[@"message"]];
                [SVProgressHUD dismissWithDelay:SVPROGRESSHUDTIME];
            }
        }
        
    } failure:^(NSError * _Nonnull err) {
        
        [SVProgressHUD showErrorWithStatus:@"注册失败"];
        [SVProgressHUD dismissWithDelay:SVPROGRESSHUDTIME];
        
    }];
    
}

//点击页面空白调用此方法
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self cancelTextEdit];
}

//键盘弹出后将视图向上移动
-(void)keyboardWillShow:(NSNotification *)note
{
    NSDictionary *info = [note userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    
    //目标视图UITextField
    CGRect frame = self.view.frame;
    int y = frame.origin.y + frame.size.height - (self.view.frame.size.height - keyboardSize.height/2);
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    if(y > 0)
    {
        self.view.frame = CGRectMake(0, -y, self.view.frame.size.width, self.view.frame.size.height);
    }
    [UIView commitAnimations];
}

//键盘隐藏后将视图恢复到原始状态
-(void)keyboardWillHide:(NSNotification *)note
{
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [UIView commitAnimations];
}

#pragma mark -- 取消输入框编辑状态
-(void)cancelTextEdit
{
    [self.regView.nameText resignFirstResponder];
    [self.regView.emailText resignFirstResponder];
    [self.regView.passText resignFirstResponder];
}

#pragma mark -- 去登陆
-(void)clickGoToLogin
{
    [self.navigationController pushViewController:[NSClassFromString(@"LoginViewController") new] animated:YES];
}

#pragma mark -- 选择头像
-(void)selectHeadImg
{
    NSUInteger sourceType = 0;
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    
    UIImagePickerController *pc = [[UIImagePickerController alloc] init];
    pc.view.backgroundColor = [UIColor whiteColor];
    pc.allowsEditing = YES;
    pc.delegate = self;
    pc.navigationBarHidden = YES;
    pc.sourceType = sourceType;
    [self presentViewController:pc animated:YES completion:nil];
}

#pragma mark - UIImagePickerController
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    self.imgdata = image;
    
    if(!image)
    {
        self.regView.textLabel.hidden = NO;
        _isImg = 0;
    }
    else
    {
        self.regView.textLabel.hidden = YES;
        self.regView.imgmageView.image = image;
        _isImg = 1;
    }
}


#pragma mark - 当用户选取完成后,调用
-(void) imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
